package com.demo.web;

import com.demo.common.Constants;
import com.demo.dto.ListResult;
import com.demo.dto.Pagination;
import com.demo.entity.*;
import com.demo.entity.Role;
import com.demo.entity.SaleLevel;
import com.demo.entity.User;
import com.demo.service.IPermissionService;
import com.demo.service.IRoleService;
import com.demo.service.ISaleLevelService;
import com.demo.vo.UserVo;
import com.demo.entity.UserRole;
import com.demo.service.IUserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import com.demo.dto.BaseResult;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("/admin/user")
public class UserController {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private IUserService userService;

    @Autowired
    private IRoleService roleService;

    @Autowired
    private IPermissionService permissionService;
    @Autowired
    private ISaleLevelService slService;

    /**
     * 用户创建
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/create", method = RequestMethod.POST)
    public BaseResult<Object> create(User user) {
        User u = new User();
        BaseResult<Object> res;
        u.setUserName(user.getUserName());
        User us = userService.queryUserByPhoneOrUserName(u);
        if (us != null) {
            return new BaseResult(false, "用户名已占用!", 403);
        }
        u.setUserName(null);
        u.setPhone(user.getPhone());
        User usv = userService.queryUserByPhoneOrUserName(u);
        if (usv != null) {
            return new BaseResult(false, "手机号已占用!", 403);
        }
        UserVo vo = new UserVo();
        vo.setComid(user.getComid());
        int number = userService.queryCountByComId(vo);
        user.setPassword((user.getPassword())); // 密码加密
        String jobNum = "" ;
        int len = (user.getComid()+jobNum).length();
        for (int i = 0; i < 3 - len; i++) { //企业ID3位，不足3位用0补齐
            jobNum += "0";
        }
        jobNum += user.getComid();

        String number_ = "" + (number+1);
        for (int i = 0; i < 5 - number_.length(); i++) { //工号5位
            jobNum += "0";
        }
        jobNum += number_;
//        jobNum = String.valueOf(user.getComid()).length()
        user.setJobNum(jobNum); // 密码加密
        int service_res = userService.insertSelective(user);
        res = new BaseResult(true, service_res);
        logger.info("查询用户~~~~" + user.getJobNum());
        return res;
    }

    @ResponseBody
    @RequestMapping(value = "/reset", method = RequestMethod.POST)
    public BaseResult<Object> reset(User user, HttpSession session) {
        User u = (User) session.getAttribute(Constants.USER);
        if (u == null) {
            return new BaseResult(false, "请登录!", 401);
        }
        user.setId(u.getId());
        int service_res = userService.updateByPrimaryKeySelective(user);

        BaseResult<Object> res = new BaseResult(true, service_res);
        logger.info("查询用户~~~~" + user.getJobNum());
        return res;
    }

    @ResponseBody
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    public BaseResult<Integer> delete(User user) {
        user.setStatus("3");
        int service_res = userService.updateByPrimaryKeySelective(user);
        BaseResult<Integer> res = new BaseResult<Integer>(true, service_res);
        return res;
    }

    /**
     * 离职
     *
     * @param user
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/off", method = RequestMethod.POST)
    public BaseResult<Integer> off(User user) {
        user.setStatus("0");
        int service_res = userService.updateByPrimaryKeySelective(user);
        BaseResult<Integer> res = new BaseResult<Integer>(true, service_res);
        return res;
    }

    @ResponseBody
    @RequestMapping(value = "/on", method = RequestMethod.POST)
    public BaseResult<Integer> on(User user) {
        user.setStatus("1");
        int service_res = userService.updateByPrimaryKeySelective(user);
        BaseResult<Integer> res = new BaseResult<Integer>(true, service_res);
        return res;
    }

    @ResponseBody
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public BaseResult<Integer> update(User user) {
        int service_res = userService.updateByPrimaryKeySelective(user);
        BaseResult<Integer> res = new BaseResult<Integer>(true, service_res);
        return res;
    }

    /***
     * 更新用户角色
     * @param id
     * @param roles
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/role_update", method = RequestMethod.POST)
    public BaseResult<Object> roleUpdate(String id, String roles) {
        if (id != null || !"".equals(id) || roles.length() == 0) {
            userService.deleteByUserId(Integer.valueOf(id));
            String[] roleArr = roles.split(",");
            List<UserRole> list = new ArrayList<UserRole>();
            for (String role : roleArr) {
                UserRole ur = new UserRole();
                ur.setRoleId(Integer.valueOf(role));
                ur.setUserId(Integer.valueOf(id));
                list.add(ur);
            }
            return new BaseResult<Object>(true, userService.addBatch(list));

        } else {
            return new BaseResult<Object>(false, "参数错误", 403);
        }
    }

    @ResponseBody
    @RequestMapping(value = "/get_user_role", method = RequestMethod.GET)
    public ListResult<List> getUserRole(String id) {
        List<Role> list = roleService.getRolesByUserID(Integer.valueOf(id));
        ListResult<List> res = new ListResult(true, list);
        return res;
    }

    @ResponseBody
    @RequestMapping(value = "/modify", method = RequestMethod.POST)
    public BaseResult<User> modify(User user) {
        BaseResult<User> res = new BaseResult<User>(true, new User());
        logger.info("查询用户~~~~" + user.getJobNum());
        return res;
    }

    /***
     * 分页查询
     * @param user
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/query", method = RequestMethod.GET)
    public ListResult query(UserVo user) {
        List<User> list = userService.queryByPage(user);
        int total = userService.queryCount(user);
        user.getPage();
        Pagination page = new Pagination(user.getPage(), total, user.getSize());
        ListResult res = new ListResult(true, list);
        res.setPage(page);

        return res;
    }

    /**
     * 营运
     *
     * @param user
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/operator", method = RequestMethod.GET)
    public ListResult operator(UserVo user) {
        List<User> list = userService.queryByPage(user);
        int total = userService.queryCount(user);

        Pagination page = new Pagination(user.getPage(), total, user.getSize());
        ListResult res = new ListResult(true, list);
        res.setPage(page);

        return res;
    }

    @ResponseBody
    @RequestMapping(value = "/logout", method = RequestMethod.GET)
    public BaseResult<User> logout(User arg, HttpSession session) {
        BaseResult<User> res;
        session.setAttribute(Constants.USER, null);
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        res = new BaseResult(true, "success");
        return res;
    }

    @ResponseBody
    @RequestMapping(value = "/nologin", method = {RequestMethod.POST, RequestMethod.GET})
    public BaseResult<String> nologin(@ModelAttribute UserVo user, HttpServletRequest request) {

        return new BaseResult<String>(false, "未登录!", 401);
    }

    @ResponseBody
    @RequestMapping(value = "/failure", method = {RequestMethod.POST, RequestMethod.GET})
    public BaseResult<String> failure(@ModelAttribute UserVo user, HttpServletRequest request) {

        return new BaseResult<String>(false, "无权操作,请向超级管理员申请此操作权限!", 403);
    }

    /**
     *
     */
    @ResponseBody
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public BaseResult<User> login(@ModelAttribute UserVo user, HttpServletRequest request) {
        if (!user.getImgCode().toLowerCase().equals(request.getSession().getAttribute(Constants.KAPTCHA_SESSION_KEY).toString().toLowerCase())) {
            return new BaseResult<>(false, "图片验证码错误", 403);
        }
        if (user.getUserName() == null || user.getPassword() == null) {
            return new BaseResult<>(false, "参数非法!", 403);
        }
        user.setPhone(null);
        UserVo loginUser = userService.queryUserByPhoneOrUserName(user);

        if (loginUser == null) {
            return new BaseResult<>(false, "用户不存在", 403);
        }
        if (!loginUser.getPassword().equalsIgnoreCase(user.getPassword())) {
            return new BaseResult<>(false, "密码错误", 403);
        }
        if (!"1".equals(loginUser.getStatus())) {
            return new BaseResult<>(false, "账户状态异常!", 403);
        }
        try {
            loginUser.setRoles(roleService.getRolesByUserID(loginUser.getId()));
            loginUser.setPermissions(permissionService.getPermissionByUserID(loginUser.getId()));
            Subject subject = SecurityUtils.getSubject();
            UsernamePasswordToken token = new UsernamePasswordToken(loginUser.getUserName(), loginUser.getPassword());
            subject.login(token);

            request.getSession().setAttribute(Constants.USER, loginUser);
        } catch (Exception ex) {
            logger.error(ex.getMessage());
        }

        return new BaseResult<>(true, loginUser);
    }

    /***
     * 获取登录用户信息
     * @param user
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/get_current", method = RequestMethod.GET)
    public BaseResult getCurrent(@ModelAttribute User user, HttpSession session) {
        UserVo user_ = (UserVo) session.getAttribute(Constants.USER);
        if (user_ != null && user_.getId() != 0) {
            return new BaseResult(true, user_);
        } else {
            return new BaseResult<UserVo>(false, "未登录", 401);
        }
    }

    /**
     * 获取会员等级
     *
     * @param session
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getSaleLevel", method = RequestMethod.GET)
    public ListResult<SaleLevel> getSaleLevel(HttpSession session) {
        List list = slService.selectAll();
        return new ListResult(true, list);
    }

    @ResponseBody
    @RequestMapping(value = "/saveSaleLevel", method = RequestMethod.POST)
    public BaseResult<Object> saveSaleLevel(String ids, String percents, HttpSession session) {
        UserVo user_ = (UserVo) session.getAttribute(Constants.USER);
        if (user_ == null) {
            return new BaseResult(false, "未登录", 401);
        }
        String[] id = ids.split(",");
        String[] percent = percents.split(",");
        for (int i = 0; i < id.length; i++) {
            SaleLevel sl = new SaleLevel();
            sl.setId(Integer.valueOf(id[i]));
            sl.setPercent(Double.valueOf(percent[i]));
            slService.updateByPrimaryKeySelective(sl);
        }
        return new BaseResult(true, "");
    }

}
